package lesson06;

public class MyBlockingQueue {
    public   static int[] elementData=null;
    private volatile static   int size=0;
    private volatile static  int tail=0;
    private  volatile static  int head=0;

    public  MyBlockingQueue(int size1){
        if(size1<=0) throw new RuntimeException("size必须大于0");
        else {
            elementData = new int[size1];
        }
    }

    public synchronized void put(int num) throws InterruptedException {


            //唤醒之后在while一次，防止多个线程同时唤醒
            while (size==elementData.length){
                //等待
                this.wait();
            }
                elementData[tail]=num;
                tail++;

                if(tail>=elementData.length)
                    tail=0;
            size++;
            this.notifyAll();

    }

    public synchronized int  talk() throws InterruptedException {
        int value=0;
        while (size==0){
            this.wait();
        }
        value=elementData[head];
        head++;
        if(head==elementData.length) head=0;
        size--;
        this.notifyAll();
        return value;
    }


}
